<template>
  <Transition :name="transitionName" @after-leave="destoryComponent" @enter="updateHeight">
    <div ref="messageRef" v-show="visible" class="my-message" :class="{
      [`my-message--${type}`]: type,
      'is-close': showClose
    }" role="alert" :style="cssStyle" @mouseenter="clearTimer" @mouseleave="startTimer">
      <div class="my-message__content">
        <slot>
          <RenderVnode :v-node="message" v-if="message" />
        </slot>
      </div>
      <div class="my-message__close" v-if="showClose">
        <Icon icon="fa-xmark" @click.stop="visible = false" />
      </div>
    </div>
  </Transition>
</template>

<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import RenderVnode from '../Common/RenderVnode'
import Icon from '../Icon/Icon.vue'
import type { MessageProps } from './types'
import { getLastBottomOffset } from './method'
import useEventListener from '@/hooks/useEventListener'
defineOptions({
  name: 'MyMessage'
})
const props = withDefaults(defineProps<MessageProps>(), {
  type: 'info',
  duration: 3000,
  offset: 20,
  transitionName: 'fade-up'
})
const visible = ref(false)
const messageRef = ref<HTMLDivElement>()
const heigth = ref(0)
const lastOffset = computed(() => getLastBottomOffset(props.id))
const topOffset = computed(() => props.offset + lastOffset.value)
const bottomOffset = computed(() => heigth.value + topOffset.value)
const cssStyle = computed(() => ({
  top: topOffset.value + 'px',
  zIndex: props.zIndex
}))
let timer: any
function startTimer() {
  if (props.duration === 0) return
  timer = setTimeout(() => {
    visible.value = false
  }, props.duration)
}
function clearTimer() {
  clearTimeout(timer)
}
onMounted(() => {
  visible.value = true
  startTimer()
  // await nextTick()
  // heigth.value = messageRef.value!.getBoundingClientRect().height
})
function keydown(e: Event) {
  const event = e as KeyboardEvent
  if (event.code === 'Escape') {
    visible.value = false
  }
}
useEventListener(document, 'keydown', keydown)
// watch(visible, (newValue) => {
//   if (!newValue) {
//     props.onDestory()
//   }
// })
function destoryComponent() {
  props.onDestory()
}
function updateHeight() {
  heigth.value = messageRef.value!.getBoundingClientRect().height
}
defineExpose({
  bottomOffset,
  visible
})
</script>

<style scoped></style>
